<template>
  <div class="padding flex direction-column height-100">
    <el-form class="search-form" inline :model="qs">
      <el-form-item label="关键字">
        <el-input v-model="qs.keyword" placeholder="用户名/登录账号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="onSearch">查询</el-button>
        <el-button icon="el-icon-refresh" @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="button-group">
      <el-button type="primary" icon="el-icon-plus" @click="add">新增</el-button>
      <el-button v-if="showBindRoleButton" type="primary" icon="el-icon-set-up" @click="bindRole">绑定角色</el-button>
      <el-button type="primary" icon="el-icon-key" @click="resetPsw">重置密码</el-button>
      <el-button type="primary" icon="el-icon-download" @click="exportData">导出</el-button>
    </div>
    <div class="flex-1 overflow-auto dark-table-wrapper">
      <el-table
        v-loading="loading" :data="lists"
         height="100%"
        :header-cell-style="{
          backgroundColor: themeColor,
          color: 'white'
        }"
        @selection-change="selection = $event"
      >
        <div slot="empty" class="empty-lists">
          <i class="i-custom:search"></i>
          <span class="empty-text">暂无数据</span>
        </div>
        <el-table-column type="selection" width="80"></el-table-column>
        <el-table-column v-for="column in columns" :key="column.prop" v-bind="column">
          <template v-if="column.prop === 'profilePhoto'" #default="{ row }">
            <el-image
              v-if="row[column.prop]"
              :src="row[column.prop]" alt="" fit="cover" class="column-image"
              :preview-src-list="[row[column.prop]]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="id" width="120px" align="center">
          <template #default="{ row }">
            <td-button title="编辑" @click="edit(row)">
              <i class="i-custom:editor"></i>
            </td-button>
            <td-button
              title="删除"
              class="del-btn"
              icon-style="color: var(--danger-color);border-color: var(--danger-color);"
              @click="del(row)"
            >
              <i class="i-custom:ashbin"></i>
            </td-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-pagination
      class="pagination" layout="total,sizes,prev,pager,next"
      background
      :current-page.sync="pagination.pageNumber"
      :page-size="pagination.pageSize" :total="pagination.total"
      @current-change="onCurrentPage" @size-change="onSizeChange"
    ></el-pagination>
    <operate-modal
      ref="modal" :modal-title="modalTitle" :data="modalData" @save-success="onSearch"
    ></operate-modal>
    <select-role-modal
      v-if="selectedUserIds && selectedUserIds.length > 0"
      ref="selectRoleModal"
      :user-ids="selectedUserIds"
      :modal-data="roleModalData"
      @save-success="onSaveSuccess"
    ></select-role-modal>
  </div>
</template>

<script>
import TdButton from '@/components/td-button'
import OperateModal from './operate-modal'
import SelectRoleModal from './select-role-modal'
import { queryList, delUser, batchResetPassWord } from '@/api/sysUser'
import { validateSelection, confirmDel } from '@/utils'
import { simpleJson2Sheet } from '@/utils/sheet'

const api = {
  queryList,
  delUser,
  batchResetPassWord
}
export default {
  name: 'user-management',
  components: {
    TdButton,
    OperateModal,
    SelectRoleModal
  },
  props: {
    showBindRoleButton: {
      type: Boolean,
      default: true,
    }
  },
  data () {
    return {
      qs: {
        keyword: ''
      },
      loading: false,
      lists: [],
      columns: [
        {
          label: '用户名',
          prop: 'userName'
        },
        {
          label: '账号',
          prop: 'loginName'
        },
        {
          label: '手机号',
          prop: 'phone'
        },
        {
          label: '所属企业',
          prop: 'tenantName',
        },
        {
          label: '账号类型',
          prop: 'accountTypeText'
        },
        {
          label: '头像',
          prop: 'profilePhoto'
        },
        {
          label: '绑定的角色',
          prop: 'roleName'
        },
      ],
      pagination: {
        pageNumber: 1,
        pageSize: 10,
        total: 0
      },
      selection: [],
      modalTitle: '',
      modalData: {},
      roleModalData: {},
    }
  },
  computed: {
    themeColor () {
      return this.$store.state.user.theme
    },
    selectedUserIds () {
      return this.selection.map(v => v.id)
    }
  },
  mounted () {
    this.getLists()
  },
  methods: {
    reload () {
      this.onReset()
    },
    getLists () {
      const {
        pageNumber,
        pageSize
      } = this.pagination
      const params = {
        pageNumber,
        pageSize,
        loginName: this.qs.keyword
      }
      this.loading = true
      return api.queryList(params).then(res => {
        if (res.code === 200) {
          (res.data.records || []).forEach(v => {
            // eslint-disable-next-line
            v.accountTypeText = ['', '政府端', '企业端'][v.accountType]
          })
          this.lists = res.data.records
          this.pagination = {
            ...this.pagination,
            pageNumber: res.data.current,
            pageSize: res.data.size,
            total: res.data.total
          }
        }
      }).finally(() => {
        this.loading = false
      })
    },
    onCurrentPage () {
      this.getLists()
    },
    onSizeChange (size) {
      this.pagination.pageSize = size
      this.$nextTick(() => {
        this.getLists()
      })
    },
    exportData () {
      const fileName = '登录账号表.xlsx'
      const lists = this.lists.map(v => ({
        id: v.id,
        userName: v.userName,
        loginName: v.loginName,
        accountType: v.accountType,
        tenantName: v.tenantName,
        phone: v.phone,
        role: v.roleId
      }))
      const headers = [
        ['ID', '用户名', '登录账号', '账号类型', '所属企业', '手机号', '角色']
      ]
      simpleJson2Sheet(fileName, headers, lists)
    },
    onSearch () {
      this.pagination.pageNumber = 1
      this.$nextTick(() => {
        this.getLists()
      })
    },
    onReset () {
      this.qs.keyword = ''
      this.onSearch()
    },
    onSaveSuccess () {
      this.getLists();
    },
    add () {
      this.modalTitle = '新增用户'
      this.modalData = {}
      this.$nextTick(() => {
        this.$refs.modal.open()
      })
    },
    edit (row) {
      this.modalTitle = '编辑用户'
      this.modalData = {
        id: row.id,
        userName: row.userName,
        phone: row.phone,
        email: row.email,
        loginName: row.loginName,
        accountType: row.accountType,
        profilePhoto: row.profilePhoto,
        tenantId: row.tenantId,
        roleId: row.roleId,
      }
      this.$nextTick(() => {
        this.$refs.modal.open()
      })
    },
    del (row) {
      confirmDel(this).then(() => {
        api.delUser(row.id).then(res => {
          if (res.code === 200) {
            this.reload()
            this.$message.success('删除成功')
          }
        })
      }).catch(() => {})
    },
    bindRole () {
      validateSelection(this).then(selection => {
        this.roleModalData = { ...selection[0] }
        this.$nextTick(() => {
          this.$refs.selectRoleModal.open()
        })
      }).catch(() => {})
    },
    resetPsw () {
      validateSelection(this).then(selection => {
        const userIds = this.selectedUserIds
        api.batchResetPassWord(userIds).then(res => {
          if (res.code === 200) {
            this.$message.success('重置成功')
          }
        })
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>

</style>
